import socket
from tlv import tlv_builder


class SocketUtils(object):
    tp = tlv_builder.TlvBuilder()

    def socket_client(self, server_info, data, timeout=2):
        if server_info["ip"] is None or server_info["port"] is None:
            return
        if data is None:
            return
        result = 10015
        # address = (server_info["ip"], server_info["port"])
        address = (server_info['ip'], server_info['port'])
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(address)
        s.settimeout(timeout)
        print(data)
        if isinstance(data, str):
            s.send(data.encode("utf-8"))
        else:
            s.send(data)
        try:
            a, ADDR = s.recvfrom(1024)
            if self.tp.tlv_result_parser(a):
                result = 666666
        except socket.timeout:
            result = 20020
            s.close()
            return result
        s.close()
        return result


if __name__ == "__main__":
    a = SocketUtils()
    s_info = {"ip": "192.168.1.199", "port": 2000}
    data = "52454313"
    print(a.socket_client(s_info, data))
